package com.von.relxdemo.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.von.relxdemo.service.DealService;
import com.von.relxdemo.service.request.OperateReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * 表达式解析
 */
@Service
public class DealServiceImp implements DealService {
    @Autowired
    private OperateFactory operateFactory;

    @Override
    public Integer dealData(String expression) {
        if(ObjectUtils.isEmpty(expression)){
            throw new RuntimeException("表达式不能为空");
        }
        String[] arr = expression.split(" ");
        if(arr.length < 3){
            throw new RuntimeException("表达式不完整");
        }

        int firstNum = 0;
        String operateStr = null;
        int secondNum = 0;
        OperateReq req = new OperateReq();
        for(int i = 0; i < arr.length; i++){
            int mod = i % 2;
            String numStr = arr[i];
            if(i == arr.length-1 && !NumberUtil.isNumber(numStr)){
                throw new RuntimeException("表达式不是以数字结尾");
            }

            if(mod == 1){
                operateStr = numStr;
                if(!operateFactory.checkOperateType(operateStr)){
                    throw new RuntimeException("运算符:"+operateStr+"不存在");
                }
            }else if(mod == 0){
                if(!NumberUtil.isNumber(numStr)){
                    throw new RuntimeException("操作数:"+numStr+"不是数字类型");
                }
                int num = Integer.parseInt(arr[i]);
                if(i < 1){
                    firstNum = num;
                    continue;
                }
                secondNum = num;
                req.setFirstNum(firstNum);
                req.setSecondNum(secondNum);
                firstNum = operateFactory.getOperateService(operateStr).cal(req);
            }
        }
        return firstNum;
    }
}
